import json
import random
from datetime import datetime, timedelta

import requests
from flask import Blueprint, current_app, jsonify, render_template
from dateutil.parser import parse
from applications.common.utils.http import success_api, fail_api
from applications.models import PoliceModels

scene_bp = Blueprint('scene', __name__, url_prefix='/scene')


@scene_bp.get('/')
# @authorize("admin:scene:main", log=True)
def main():
    return render_template('admin/scene/main.html')


@scene_bp.get('/user/<int:user_id>')
def get_by_user_page(user_id):
    police = PoliceModels.query.filter_by(id=user_id).one_or_none()
    if police is None:
        return fail_api(msg='找不到警员信息')
    return render_template('admin/scene/result.html', police=police)


@scene_bp.get('/user/data/<code>/<name>')
def get_record_by_code(code, name):
    body = {
        "code": code,
        "name": name
    }
    response = requests.post(url=current_app.config['SCENE_URL'] + '/operate/api/v1/searchexperiencetime',
                             json=body)
    try:
        data = json.loads(response.text)
        res = {
            "code": 0,
            "count": len(data['data']),
            "limit": 10,
            "data": data['data']
        }
        return res
    except:
        return fail_api(msg='查询失败')


# 根据用户编号，姓名，开始时间，结束时间查询体征信息
@scene_bp.get('/detail/<code>/<name>/<starttime>/<endtime>')
def get_record_by_time(code, name, starttime, endtime):
    body = {
        "code": code,
        "name": name,
    }
    reponse = requests.post(url=current_app.config['SCENE_URL'] + '/operate/api/v1/adduser', json=body)
    try:
        data = json.loads(reponse.text)
        user_id = data['userid']
    except:
        return fail_api(msg='找不到用户信息')

    try:
        start = parse(starttime) + timedelta(hours=8)
        end = parse(endtime) + timedelta(hours=8)
        start_string = start.strftime("%Y-%m-%d %H:%M:%S")
        end_string = end.strftime("%Y-%m-%d %H:%M:%S")
    except:
        return fail_api(msg='时间格式错误')
    body = {
        "userid": user_id,
        "starttime": start_string,
        "endtime": end_string
    }
    response = requests.post(url=current_app.config['SCENE_URL'] + '/operate/api/v1/historyexperiencedata', json=body)
    try:
        data = json.loads(response.text)
        for d in data['data']:
            d['date'] = (parse(d['date']) + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
    except:
        return fail_api(msg='查询失败')
    return render_template('admin/scene/result_detail.html', records=data['data'])
